<template>
	<cl-page>
		<view class="footprint-page">
			<!-- 标题栏 -->
			<view class="header">
				<text class="title">浏览足迹</text>
				<view class="actions">
					<text class="clear-btn" @tap="clearAll" v-if="footprintList.length > 0">
						清空
					</text>
				</view>
			</view>

			<!-- 统计信息 -->
			<view class="stats-card" v-if="footprintList.length > 0">
				<view class="stat-item">
					<text class="stat-number">{{ todayCount }}</text>
					<text class="stat-label">今日浏览</text>
				</view>
				<view class="stat-item">
					<text class="stat-number">{{ footprintList.length }}</text>
					<text class="stat-label">总浏览量</text>
				</view>
			</view>

			<!-- 足迹列表 -->
			<view class="content">
				<view class="footprint-list" v-if="footprintList.length > 0">
					<view class="date-group" v-for="group in groupedFootprints" :key="group.date">
						<view class="date-header">
							<text class="date-text">{{ group.dateText }}</text>
							<text class="count-text">{{ group.items.length }}个商品</text>
						</view>
						<view class="goods-grid">
							<view
								class="goods-item"
								v-for="item in group.items"
								:key="item.id"
								@tap="toGoodsDetail(item)"
							>
								<cl-image
									:src="'https://shop.sdamdyy.cn/' + (item.mainPic || '')"
									class="goods-image"
									mode="aspectFill"
									width="100%"
									height="340rpx"
									:lazy-load="true"
									fallback="/static/empty/no.jpg"
								/>
								<view class="goods-info">
									<text class="goods-name">{{
										item.title || item.oracleGoodsName
									}}</text>
									<text class="goods-spec" v-if="item.goodsSpec"
										>{{ item.goodsSpec }} {{ item.unit }}</text
									>
									<view class="goods-footer">
										<view class="price-wrap">
											<text class="goods-price" v-if="userStore.token">{{
												formatUserPrice(
													item.price,
													userStore,
													item.noDiscounts
												)
											}}</text>
											<text class="goods-price" v-else>登录查看</text>
										</view>
										<view class="view-info">
											<text class="view-count"
												>浏览{{ item.visitCount || 1 }}次</text
											>
											<text class="view-time">{{
												formatTimeAgo(item.viewTime)
											}}</text>
										</view>
									</view>
								</view>
							</view>
						</view>
					</view>
				</view>

				<cl-empty v-else :fixed="false" :height="400" text="暂无浏览记录" icon="eye" />

				<view class="loading-more" v-if="footprintList.length > 0">
					<cl-loadmore :loading="loading" :finish="!hasMore" :divider="false" />
				</view>
			</view>
		</view>
	</cl-page>
</template>

<script lang="ts" setup>
import { ref, computed } from "vue";
import { onReady, onReachBottom } from "@dcloudio/uni-app";
import { useCool } from "/@/cool";
import { useStore } from "/@/cool/store";
import { formatUserPrice } from "/@/utils/price";

const { service, router } = useCool();
const { user: userStore } = useStore();

const footprintList = ref<any[]>([]);
const currentPage = ref(1);
const pageSize = ref(20);
const loading = ref(false);
const hasMore = ref(true);
const total = ref(0);

// 计算今日浏览数
const todayCount = computed(() => {
	const today = new Date().toDateString();
	return footprintList.value.filter((item) => {
		return new Date(item.viewTime).toDateString() === today;
	}).length;
});

// 按日期分组的足迹数据
const groupedFootprints = computed(() => {
	const groups: any[] = [];
	const groupMap = new Map();

	footprintList.value.forEach((item) => {
		const date = new Date(item.viewTime).toDateString();
		if (!groupMap.has(date)) {
			groupMap.set(date, {
				date,
				dateText: formatDate(item.viewTime),
				items: [],
			});
			groups.push(groupMap.get(date));
		}
		groupMap.get(date).items.push(item);
	});

	return groups.sort((a, b) => new Date(b.date).getTime() - new Date(a.date).getTime());
});

// 格式化日期
function formatDate(dateStr: string) {
	const date = new Date(dateStr);
	const today = new Date();
	const yesterday = new Date(today);
	yesterday.setDate(today.getDate() - 1);

	if (date.toDateString() === today.toDateString()) {
		return "今天";
	} else if (date.toDateString() === yesterday.toDateString()) {
		return "昨天";
	} else {
		return date.toLocaleDateString("zh-CN", {
			month: "long",
			day: "numeric",
		});
	}
}

// 格式化时间（多久前）
function formatTimeAgo(dateStr: string) {
	const date = new Date(dateStr);
	const now = new Date();
	const diff = now.getTime() - date.getTime();

	const minutes = Math.floor(diff / 60000);
	const hours = Math.floor(diff / 3600000);
	const days = Math.floor(diff / 86400000);

	if (minutes < 1) {
		return "刚刚";
	} else if (minutes < 60) {
		return `${minutes}分钟前`;
	} else if (hours < 24) {
		return `${hours}小时前`;
	} else if (days < 7) {
		return `${days}天前`;
	} else {
		return date.toLocaleDateString("zh-CN", {
			month: "numeric",
			day: "numeric",
		});
	}
}

// 跳转商品详情
function toGoodsDetail(item: any) {
	console.log('足迹点击跳转，商品数据:', item);
	console.log('跳转的商品ID:', item.id);
	router.push(`/pages/goods/detail?id=${item.id}`);
}

// 清空足迹
function clearAll() {
	uni.showModal({
		title: "提示",
		content: "确定要清空所有浏览记录吗？",
		success: async (res) => {
			if (res.confirm) {
				try {
					// 获取所有足迹ID
					const ids = footprintList.value.map((item) => item.id);
					if (ids.length > 0) {
						// 批量删除
						await service.user.footprint.delete({ ids });
					}
					footprintList.value = [];
					total.value = 0;
					hasMore.value = false;
					uni.showToast({ title: "清空成功", icon: "success" });
				} catch (error) {
					console.error("清空足迹失败:", error);
					uni.showToast({ title: "清空失败", icon: "error" });
				}
			}
		},
	});
}

// 加载足迹数据
async function loadFootprints(reset = false) {
	if (loading.value) return;

	if (reset) {
		currentPage.value = 1;
		hasMore.value = true;
	}

	if (!hasMore.value) return;

	loading.value = true;

	try {
		// 获取足迹数据
		const res = await service.user.footprint.page({
			page: currentPage.value,
			size: pageSize.value,
		});

		const list = res.list || [];

		// 过滤掉价格为零的商品
		const filteredList = list.filter((item) => item.price && Number(item.price) > 0);

		if (reset) {
			footprintList.value = filteredList;
		} else {
			footprintList.value.push(...filteredList);
		}

		// 更新分页信息
		total.value = res.pagination?.total || 0;
		hasMore.value = footprintList.value.length < total.value;

		if (hasMore.value) {
			currentPage.value++;
		}
	} catch (error) {
		console.error("加载足迹数据失败:", error);
		uni.showToast({ title: "加载失败", icon: "error" });
		hasMore.value = false;
	} finally {
		loading.value = false;
	}
}

// 上拉加载更多
onReachBottom(() => {
	if (!loading.value && hasMore.value) {
		loadFootprints();
	}
});

onReady(() => {
	loadFootprints(true);
});
</script>

<style lang="scss" scoped>
.footprint-page {
	background-color: #f5f5f5;
	min-height: 100vh;
}

.header {
	display: flex;
	align-items: center;
	justify-content: space-between;
	padding: 24rpx 32rpx;
	background-color: #ffffff;
}

.title {
	font-size: 36rpx;
	font-weight: 600;
	color: #1a1a1a;
}

.clear-btn {
	font-size: 28rpx;
	color: #ff4757;
	padding: 8rpx 16rpx;

	&:active {
		opacity: 0.7;
	}
}

.stats-card {
	display: flex;
	margin: 20rpx 32rpx;
	background-color: #ffffff;
	border-radius: 16rpx;
	padding: 32rpx;
	gap: 100rpx;
	box-shadow: 0 2rpx 8rpx rgba(0, 0, 0, 0.05);
}

.stat-item {
	text-align: center;
	flex: 1;
}

.stat-number {
	display: block;
	font-size: 48rpx;
	font-weight: 700;
	color: #667eea;
	line-height: 1;
	margin-bottom: 12rpx;
}

.stat-label {
	font-size: 24rpx;
	color: #666;
}

.content {
	padding: 0 32rpx 32rpx;
}

.date-group {
	margin-bottom: 32rpx;
}

.date-header {
	display: flex;
	align-items: center;
	justify-content: space-between;
	margin-bottom: 20rpx;
	padding: 0 8rpx;
}

.date-text {
	font-size: 30rpx;
	font-weight: 600;
	color: #1a1a1a;
}

.count-text {
	font-size: 24rpx;
	color: #999;
}

.goods-grid {
	display: grid;
	grid-template-columns: repeat(2, 1fr);
	gap: 20rpx;
}

.goods-item {
	background-color: #ffffff;
	border-radius: 16rpx;
	overflow: hidden;
	transition: all 0.3s ease;
	box-shadow: 0 2rpx 8rpx rgba(0, 0, 0, 0.05);

	&:active {
		transform: scale(0.98);
	}
}

.goods-image {
	width: 100%;
	height: 340rpx;
	background-color: #f5f5f5;
}

.goods-info {
	padding: 20rpx;
	display: flex;
	flex-direction: column;
	gap: 8rpx;
}

.goods-name {
	font-size: 28rpx;
	color: #1a1a1a;
	font-weight: 500;
	line-height: 1.4;
	overflow: hidden;
	text-overflow: ellipsis;
	display: -webkit-box;
	-webkit-line-clamp: 2;
	line-clamp: 2;
	-webkit-box-orient: vertical;
}

.goods-spec {
	font-size: 24rpx;
	color: #666;
}

.goods-footer {
	margin-top: 8rpx;
}

.price-wrap {
	margin-bottom: 8rpx;
}

.goods-price {
	font-size: 32rpx;
	font-weight: 600;
	color: #ff4757;
}

.view-info {
	display: flex;
	align-items: center;
	justify-content: space-between;
	font-size: 22rpx;
	color: #999;
}

.view-count {
	color: #666;
}

.view-time {
	color: #999;
}
</style>
